var wxCharts = require('../../../utils/wxcharts.js');
import { getStatisticalAggregate, getStatisticalDay, getStatisticalYear, getStatisticalMonth } from '../../../api/expense'
var app = getApp();
var lineChart = null;
var radarChart = null;
var pieChart = null;
var columnChart = null;

Page({
  data: {
    windowWidth: 320,
    tab: ['月', '总'],
    TabCur: 0,
    start_date: '',
    query_day: {
      start_date: '2022-04-01',
      end_date: '2022-04-30'
    },
    // 柱状图
    isMainChartDisplay: true,
    chartTitle: '年支出金额(点击数据每一项查看详情)',
    year_spending_data: {
      year_spemding: {
        title: '年支出金额',
        data: [],
        categories: []
      },
      sub: {
        '1994': {
          title: '1994年每月支出金额',
          data: [],
          categories: []
        }
      }
    }
  },

  onLoad: function (options) {
    var windowWidth = 320;
    try {
      var sys = wx.getSystemInfoSync();
      const windowWidth = sys.windowWidth
      this.setData({
        windowWidth: windowWidth
      })
    } catch (e) {
      console.error('getSystemInfoSync failed!');
    }
    const year = options['year'], month = options['month']
    const start_date = `${year}-${month}`
    this.setData({
      start_date: [year, month],
      [`query_day.start_date`]: `${start_date}-01`,
      [`query_day.end_date`]: `${this._next_month(start_date)}-01`,
    })
    
    this._fetchStatisticalDayData(this.data.query_day)
    this._fetchStatisticalYearData()
  },

  _next_month(date) {
    const year_month = date.split('-')
    let year = Number(year_month[0])
    let month = Number(year_month[1]) + 1

    if (month > 12) {
      month = 1
      year = year + 1
    }
    return `${year}-${month}`
  },

  DateChange(e) {
    const date = e.detail.value
    const year_month = date.split('-')
    this.setData({
      start_date: year_month,
      [`query_day.start_date`]: `${date}-01`,
      [`query_day.end_date`]: `${this._next_month(date)}-01`
    })
    this._fetchStatisticalDayData(this.data.query_day)

  },
  columnChartTouchHandler: function (e) {
    var index = columnChart.getCurrentDataIndex(e);
    const year_spending_data = this.data.year_spending_data
    const year = year_spending_data.year_spemding.categories[index]
    if (index > -1 && index < year_spending_data.year_spemding.categories.length && this.data.isMainChartDisplay) {
      this.setData({
        isMainChartDisplay: false,
        chartTitle: `${year}年每月支出金额`
      });
      if (!(year in this.data.year_spending_data.sub)) {
        // 判断是否已经存在
        this._fetchStatisticalMonthData({ 'year': year })
      } else {
        const month_spending_data = this.data.year_spending_data.sub[year]
        this._updatecolumnChart(month_spending_data.categories, month_spending_data.data, year)
      }

    }
  },
  // 返回
  backToMainChart: function () {
    this.setData({
      chartTitle: '年支出金额(点击数据每一项查看详情)',
      isMainChartDisplay: true
    });
    const { categories, data, title } = this.data.year_spending_data.year_spemding
    columnChart.updateData({
      categories: categories,
      series: [{
        name: title,
        data: data,
        format: function (val, name) {
          return val.toFixed(2) + '万';
        }
      }]
    });
  },
  // 查看每月支出金额
  _updatecolumnChart(categories, data, year) {
    columnChart.updateData({
      categories: categories,
      series: [{
        name: `${year}年月支出金额`,
        data: data,
        format: function (val, name) {
          return val.toFixed(2) + '';
        }
      }]
    });
  },

  // 线性图标点击显示
  lineChartTouchHandler: function (e) {
    lineChart.showToolTip(e, {
      // background: '#7cb5ec',
      format: function (item, category) {
        return category + ' ' + item.name + ':' + item.data
      }
    });
    radarChart.showToolTip(e, {
      // background: '#7cb5ec',
      format: function (item, category) {
        return '22222'
      }
    });
  },
  // 
  _fetchStatisticalMonthData: function (query) {
    return getStatisticalMonth(query).then(res => {
      const result = {
        categories: res.data.expense.categories,
        data: res.data.expense.spending,
      }
      this.setData({
        [`year_spending_data.sub.${query.year}`]: result
      })
      this._updatecolumnChart(result.categories, result.data, query.year)
    })
  },
  _fetchStatisticalYearData: function () {
    const that = this
    return getStatisticalYear().then(res => {
      const expense = res.data.expense
      this.setData({
        [`year_spending_data.year_spemding.categories`]: expense.categories,
        [`year_spending_data.year_spemding.data`]: expense.spending,
      })
      columnChart = new wxCharts({
        canvasId: 'columnCanvas',
        type: 'column',
        animation: true,
        categories: expense.categories,
        series: [{
          name: '年支出金额',
          data: expense.spending,
          format: function (val, name) {
            return val.toFixed(2) + '';
          }
        }],
        yAxis: {
          format: function (val) {
            return val;
          },
          title: '支出金额',
          min: 0
        },
        xAxis: {
          disableGrid: false,
          type: 'calibration'
        },
        extra: {
          column: {
            width: 15
          }
        },
        width: that.data.windowWidth,
        height: 200,
      });
    })
  },
  // 获取按天分组数据
  _fetchStatisticalDayData: function (query) {
    const that = this
    return getStatisticalDay(query).then(res => {

      const simulationData = res.data
      // 线性图表
      lineChart = new wxCharts({
        canvasId: 'lineCanvas',
        type: 'line',
        categories: simulationData.expense.categories,
        animation: true,
        // background: '#f5f5f5',
        series: [{
          name: '支出',
          data: simulationData.expense.spending,
          format: function (val, name) {
            return val.toFixed(2);
          }
        }, {
          name: '收入',
          data: simulationData.expense.income,
          format: function (val, name) {
            return val.toFixed(2);
          }
        }],
        xAxis: {
          disableGrid: true
        },
        yAxis: {
          title: '金额 (元)',
          format: function (val) {
            return val.toFixed(2);
          },
          min: 0
        },
        width: that.data.windowWidth,
        height: 200,
        dataLabel: false,
        dataPointShape: true,
        extra: {
          lineStyle: 'curve'
        }
      });
      // 雷达图表

      if (simulationData.spending_num[0].length == 0) {
        simulationData.spending_num = [[0], [0]]
      }
      radarChart = new wxCharts({
        canvasId: 'radarCanvas',
        type: 'radar',
        categories: simulationData.spending_num[0],
        series: [{
          name: '消费次数',
          data: simulationData.spending_num[1],
          format: function (item, category) {
            return category + ' ' + item.name + ':' + item.data
          }
        }],
        width: that.data.windowWidth,
        height: 300,
        extra: {
          radar: {
            max: simulationData.spending_num[1][0] * 4 / 3
          }
        }
      });
      if (simulationData.spending_amount.length == 0) {
        simulationData.spending_amount = [{ name: '未知', data: 0 }]
      }
      // 占比
      pieChart = new wxCharts({
        animation: true,
        canvasId: 'pieCanvas',
        type: 'pie',
        series: simulationData.spending_amount,
        width: that.data.windowWidth,
        height: 300,
        dataLabel: true,
      });
      return res.data.results
    }).catch(() => {
      return []
    })
  },
  // 导航
  tabSelect(e) {
    this.setData({
      TabCur: e.currentTarget.dataset.id,
      scrollLeft: (e.currentTarget.dataset.id - 1) * 60
    })
    // this._fetchStatisticalDayData(this.data.query_day)
  }
});